package com.eqdd.yiqidian.ui.mine.qiye;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.yiqidian.MyContractInfoActivityCustom;
import com.eqdd.yiqidian.NoticeInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ContractInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.LeaveCheckerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditApplyTitleBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTwoSectionEditBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.base.EditTextActivity;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.reactivex.subscribers.DisposableSubscriber;

public class MyContractInfoActivity extends BaseActivity {
    private MyContractInfoActivityCustom dataBinding;
    private SlimAdapterEx<SlimEditBean> slimAdapterEx;
    private String contractId;
    private ArrayList<SlimEditBean> datas;
    private int status;
    private ContractInfoResultBean items;
    private List<LeaveCheckerListResultBean> checkers;
    private int who;
    private String msg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_my_contract_info);
        initTopTitleBar(View.VISIBLE, "合同详情");
    }
    @Override
    public void initData() {
        contractId = getIntent().getStringExtra("contractId");
        who = getIntent().getIntExtra(Config.WHO, 0);
        status = getIntent().getIntExtra(Config.STATUS, 0);
        initTitle();
        datas = new ArrayList<>();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.setNestedScrollingEnabled(false);
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_49, new SlimInjector<SlimEditApplyTitleBean>() {
                    @Override
                    public void onInject(SlimEditApplyTitleBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, dealText(data.getTopLeftContent()))
                                .text(R.id.tv_upper_right_content, dealText(data.getTopRightContent()))
                                .text(R.id.tv_down_content, dealText(data.getTitle()));

                    }
                })
                .register(R.layout.list_item_42, new SlimInjector<SlimTwoSectionEditBean>() {
                    @Override
                    public void onInject(SlimTwoSectionEditBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, data.getUpTitle())
                                .text(R.id.tv_upper_right_content, data.getUpContent())
                                .text(R.id.tv_down_left_content, data.getDownTitle())
                                .text(R.id.tv_down_right_content, data.getDownContent())
                                .gone(R.id.stv_bottom);

                    }
                })
                .register(R.layout.list_item_29, new SlimInjector<SlimEditEnterBean>() {
                    @Override
                    public void onInject(SlimEditEnterBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
                    @Override
                    public void onInject(SlimEditHintBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_hint_content, dealText(data.getContent()));
                    }
                }).attachTo(dataBinding.recyclerView);
        dataBinding.rbReject.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbAgree.setChecked(!isChecked);
            }
        });
        dataBinding.rbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbReject.setChecked(!isChecked);
            }
        });
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    switch (slimAdapterEx.getDataItem(position).getPosition()) {
                        case 16:
                        case 15:
                            SlimEditBean slimEditBean = slimAdapterEx.getData().get(position);
                            if (slimEditBean instanceof SlimEditEnterBean) {
                                SlimEditEnterBean slimEditEnterBean = (SlimEditEnterBean) slimEditBean;
                                Bundle bundle = new Bundle();
                                bundle.putString("content", slimEditEnterBean.getContent());
                                bundle.putString("tip", slimEditEnterBean.getTitle());
                                bundle.putString("title", slimEditEnterBean.getTitle());
                                bundle.putBoolean("canBlank", slimEditEnterBean.isCanBlank());
                                AppConstent.schemes = slimEditEnterBean.getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, position);
                            }
                            break;

                    }
                });
    }

    private void initTitle() {
        if (status==0) {
            initTopRightText("提交", v -> {
                if (checkParam()) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CONTRACT_CHECK_BY_ME)
                            .params("contractId", items.getId())
                            .params("userGuid", user.getGuid())
                            .params("message", dataBinding.etRemark.getText().toString())
                            .params("type", dataBinding.rbAgree.isChecked() ? 1 : 2)
                            .params("openBank", slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 2).getContent())
                            .params("bankCard", slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getContent())
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        setResult(Config.SUCCESS);
                                        finish();
                                    }
                                }
                            });
                } else {
                    ToastUtil.showLong(msg);
                }
            });
        }
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getContent())) {
            msg = "请输入银行卡号";
            return false;
        }
        if (TextUtils.isEmpty(dataBinding.etRemark.getText())) {
            msg = "请输入备注";
            return false;
        }
        return true;
    }

    @Override
    public void setView() {
        Flowable<HttpResult<List<LeaveCheckerListResultBean>>> flowLeaveChecker = OkGo.<HttpResult<List<LeaveCheckerListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.CONTRACT_CHECKER_LIST)
                .params("contractId", contractId)
                .converter(new JsonConverter<HttpResult<List<LeaveCheckerListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<LeaveCheckerListResultBean>>>());

        Flowable<HttpResult<ContractInfoResultBean>> flowLeaveInfo = OkGo.<HttpResult<ContractInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.CONTRACT_INFO)
                .params("contractId", contractId)
                .converter(new JsonConverter<HttpResult<ContractInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<ContractInfoResultBean>>());
        Flowable.combineLatest(flowLeaveChecker, flowLeaveInfo, (BiFunction<HttpResult<List<LeaveCheckerListResultBean>>, HttpResult<ContractInfoResultBean>, Object>) (listHttpResult, ContractInfoResultBeanHttpResult) -> {
            if (ContractInfoResultBeanHttpResult.getStatus() == 200) {
                items = ContractInfoResultBeanHttpResult.getItems();
                if (items == null) {
                    if (!dispos.isDisposed()) {
                        dispos.dispose();
                    }
                    ToastUtil.showShort("单子已删除");
                    finish();
                }
            }
            if (listHttpResult.getStatus() == 200) {
                checkers = listHttpResult.getItems();
            }
            return 1;
        })
                .subscribe(dispos);

    }

    private DisposableSubscriber dispos = new DisposableSubscriber() {
        @Override
        public void onNext(Object o) {
            datas.add(new SlimEditHintBean("合同编码", items.getContractCode(), 0));
            datas.add(new SlimEditHintBean("签订人", items.getSignatoryName(), 1));
            datas.add(new SlimEditHintBean("所在部门", items.getDepartment(), 2));
            datas.add(new SlimEditHintBean("所在岗位", items.getPost(), 3));
            datas.add(new SlimEditHintBean("入职时间", items.getSignEntryTime(), 4));
            datas.add(new SlimEditHintBean("合同类型", items.getContractType(), 5));
            datas.add(new SlimEditHintBean("合同性质", items.getContractNature(), 6));
            datas.add(new SlimEditHintBean("合同签订次数", items.getSignedNumber(), 7));
            datas.add(new SlimEditHintBean("上次合同结束原因", items.getLastReason(), 8));
            datas.add(new SlimEditHintBean("合同劳动形式", items.getContractForm(), 9));
            datas.add(new SlimTwoSectionEditBean("", "", 10, "合同开始时间", "合同结束时间", items.getContractStartTime(), items.getContractEndTime()));
            datas.add(new SlimEditHintBean("试用期", items.getProbation(), 11));
            datas.add(new SlimEditHintBean("发起人", items.getCreaterName(), 12));
            datas.add(new SlimEditHintBean("工资发放银行", items.getBank(), 13));
            for (LeaveCheckerListResultBean checker : checkers) {
                datas.add(new SlimEditApplyTitleBean(checker.getUname(), checker.getStatus() == -1 ? "等待审核" : checker.getStatus() == 2 ? "已拒绝" : "已同意",
                        checker.getMessage(), "", 14));
            }
            if (status==0) {
                datas.add(new SlimEditEnterBean("工资卡开户行", "", 15, "请输入"));
                datas.add(new SlimEditEnterBean("工资卡帐号", "", 16, "请输入").addSchemes(StaticScheme.BankCard()));
                dataBinding.llDownRoot.setVisibility(View.VISIBLE);
            } else {
                datas.add(new SlimEditHintBean("工资卡开户行", "", 15));
                datas.add(new SlimEditHintBean("工资卡帐号", items.getBankCard(), 16));
            }
            slimAdapterEx.updateData(datas);
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };

    private String dealText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.INTENT_CONTENT) {
            String content = data.getStringExtra("content");
            datas.get(requestCode).setContent(content);
            slimAdapterEx.notifyItemChanged(requestCode);
        }
    }
}
